//
//  AppDelegate.m
//  GuShiNews
//
//  Created by huachun on 2019/8/16.
//  Copyright © 2019 Jones. All rights reserved.
//

#import "AppDelegate.h"
#import "HiRootController.h"
#import "AvoidCrash.h"
#import "UINavigationBar+Awesome.h"
#import "Start_AddView.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#import "JSMSSDK.h"
#import "JANALYTICSService.h"

// 如果需要使用idfa功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>

#import "JonesSingle.h"
#import "OSSTestMacros.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate,JPUSHRegisterDelegate>{
    BOOL lin_sixinok;
}

@end

@implementation AppDelegate

static NSString *appKey  = @"a4935994a98b1f441a98632d";
static NSString *channel = @"App Store";
static BOOL isProduction = FALSE;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    lin_sixinok = NO;
    
    [self set_mainvc_App];
    [self set_color_app];
    [self jiguang_setting:launchOptions];
    [self avoidCrash];
    
    //    NSString *endpoint = @"https://oss-cn-beijing.aliyuncs.com";
    
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:
                                            OSS_ACCESSKEY_ID secretKey:OSS_SECRETKEY_ID];
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credential];
    
    [JonesSingle instance].client = client;
    [JonesSingle instance].Zan_cun_change = 0;
    
    return YES;
    
    return YES;
}


/*
 *试图主页
 */
-(void)set_mainvc_App{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [_window makeKeyAndVisible];
    
    _Root_VC                    = [HiRootController new];
    
    _window.rootViewController  = _Root_VC;
    
    if ([DEFAULTS objectForKey:ROOTSHANPINADDIMG]) {
        Start_AddView *addview          = [[Start_AddView alloc] init:[DEFAULTS objectForKey:ROOTSHANPINADDIMG]];
        addview.seletBlock              = ^(NSString *successOk){
            
        };
    }
}

-(void)set_color_app{
    //设置SVProgressHUD样式
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    [SVProgressHUD setMinimumDismissTimeInterval:2];
    [SVProgressHUD setFadeOutAnimationDuration:0];
    //状态栏前景色(白色)
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //导航背景色
    [[UINavigationBar appearance] lt_setBackgroundColor:[UIColor whiteColor]];
    
    //    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
    //隐藏导航分割线
    [[UINavigationBar appearance] setShadowImage:[UIImage new]];
    //导航item颜色
    [[UINavigationBar appearance] setTintColor:NavItemTitleColor];
    //导航title颜色
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           NavItemTitleColor, NSForegroundColorAttributeName,
                                                           nil]];
    
    //tabbar item颜色
    [[UITabBar appearance] setTintColor:NavItemTitleColor];
    //[[UITabBar appearance] setUnselectedItemTintColor:[JonesClass stringTOColor:@"#666666"]];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
}

- (void)avoidCrash {
    
    /*
     * 项目初期不需要对"unrecognized selector sent to instance"错误进行处理，因为还没有相关的崩溃的类
     * 后期出现后，再使用makeAllEffective方法，把所有对应崩溃的类添加到数组中，避免崩溃
     * 对于正式线可以启用该方法，测试线建议关闭该方法
     */
    [AvoidCrash becomeEffective];
    
    
    //    [AvoidCrash makeAllEffective];
    //    NSArray *noneSelClassStrings = @[
    //                                     @"NSString"
    //                                     ];
    //    [AvoidCrash setupNoneSelClassStringsArr:noneSelClassStrings];
    
    
    //监听通知:AvoidCrashNotification, 获取AvoidCrash捕获的崩溃日志的详细信息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealwithCrashMessage:) name:AvoidCrashNotification object:nil];
}

- (void)dealwithCrashMessage:(NSNotification *)notification {
    NSLog(@"\n🚫\n🚫监测到崩溃信息🚫\n🚫\n");
    /*
     * 在这边对避免的异常进行一些处理，比如上传到日志服务器等。
     */
}

-(void)jiguang_setting:(NSDictionary *)launchOptions{
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
        }else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    [JSMSSDK registerWithAppKey:appKey];
    [JSMSSDK setMinimumTimeInterval:180];
    
    JANALYTICSLaunchConfig * config = [[JANALYTICSLaunchConfig alloc] init];
    
    config.appKey = appKey;
    
    config.channel = @"channel";
    
    [JANALYTICSService setupWithConfig:config];
    
    [DEFAULTS removeObjectForKey:@"DUANXINCOUNT"];
}


-(void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [self stringDevicetoken:deviceToken];
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#pragma mark 以下的
-(NSString *)stringDevicetoken:(NSData *)deviceToken
{
    NSString *token = [deviceToken description];
    NSString *pushToken = [[[token stringByReplacingOccurrencesOfString:@"<"withString:@""] stringByReplacingOccurrencesOfString:@">"withString:@""] stringByReplacingOccurrencesOfString:@" "withString:@""];
    return pushToken;
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //NSLog(@"iOS10 收到远程通知:%@",userInfo);
        
        
        if (lin_sixinok) {
            [[NSNotificationCenter defaultCenter] postNotificationName:NEWS_CHAT_COUNT object:userInfo];
        }
        
    }
    
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}


// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        //NSLog(@"iOS10 收到远程通知:%@",userInfo);
        
        //        [[NSNotificationCenter defaultCenter] postNotificationName:NEW_CHAT_Key object:userInfo];
        
        if (lin_sixinok) {
            [[NSNotificationCenter defaultCenter] postNotificationName:NEWS_CHAT_COUNT object:userInfo];
        }
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    //NSLog(@"iOS10 收到远程通知:%@",userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    //NSLog(@"iOS10 收到远程通知:%@",userInfo);
    
    //    [[NSNotificationCenter defaultCenter] postNotificationName:NEW_CHAT_Key object:userInfo];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    lin_sixinok = YES;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
